package com.five.taotao.guide;


import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.five.taotao.Adapter.HeaderAdapter;
import com.five.taotao.Adapter.HoAdapter;
import com.five.taotao.Adapter.VPTabAdapter;
import com.five.taotao.Application.MyApplication;
import com.five.taotao.R;
import com.five.taotao.dao.ProductListBeanDao;
import com.five.taotao.entity.Product;
import com.five.taotao.entity.ProductList;
import com.five.taotao.guide_home.HomeShowFragment;
import com.five.taotao.product_details.ProductDetailsActivity;
import com.five.taotao.search.SearchResultActivity;
import com.five.taotao.selfwidget.CustomProgressDialog;
import com.five.taotao.util.Constants;
import com.five.taotao.util.ThreadPoolManager;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.meetme.android.horizontallistview.HorizontalListView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {

    @BindView(R.id.search)
    EditText search;
    @BindView(R.id.vp)
    ViewPager viewPager;
    @BindView(R.id.ptr)
    PullToRefreshScrollView ptr;
    @BindView(R.id.aa)
    ImageView aa;
    @BindView(R.id.imag1)
    ImageView imag1;
    @BindView(R.id.imag2)
    ImageView imag2;
    @BindView(R.id.imag3)
    ImageView imag3;
    @BindView(R.id.tabs)
    TabLayout tabs;
    @BindView(R.id.vp1)
    ViewPager vp;
    @BindView(R.id.hour)
    TextView hour;
    @BindView(R.id.min)
    TextView min;
    @BindView(R.id.second)
    TextView second;
    @BindView(R.id.scroll_lv)
    HorizontalListView scroll_lv;
    @BindView(R.id.img_ads)
    ImageView img_ads;

    @OnClick(R.id.message_search)
    public void search(View v) {
        Intent intent = new Intent(getActivity(), SearchResultActivity.class);
        intent.putExtra("search_name", search.getText().toString());
        startActivity(intent);
    }

    private View v;
    private ArrayList<ImageView> arrayList;
    private int[] imageResId; // 图片ID
    private List<View> dots; // 图片标题正文的那些点
    private int num = 600;
    private HeaderAdapter adapter;
    private DisplayMetrics dm;//屏幕尺寸管理器

    private HomeShowFragment fragment1;
    private HomeShowFragment fragment2;
    private HomeShowFragment fragment3;
    private HomeShowFragment fragment4;
    private VPTabAdapter VPAdapter;
    private List<Fragment> mDataF;
    private List<String> strings;
    private HoAdapter hoAdapter;
    private List<Product.ListBean> mData;

    private CustomProgressDialog myDialog;


    ThreadPoolManager tm = ThreadPoolManager.getInstance();//线程池管理
    ScheduledExecutorService ses = tm.getScheduledExcutorService();

    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (v == null) {
            v = inflater.inflate(R.layout.fragment_home, container, false);
            ButterKnife.bind(this, v);

            img_ads.setImageResource(R.drawable.ads);

            dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            //初始化数据
            imageResId = new int[]{R.drawable.img4, R.drawable.img5, R.drawable.img3
                    , R.drawable.img1, R.drawable.img2};
            initData();

            mData = new ArrayList<>();
            hoAdapter = new HoAdapter(mData,getActivity());
            scroll_lv.setAdapter(hoAdapter);

            loadNetData();

            ses.scheduleWithFixedDelay(new Runnable() {
                @Override
                public void run() {
                    timeHandler.sendEmptyMessage(1);
                }
            }, 0, 1000, TimeUnit.MILLISECONDS);

            adapter = new HeaderAdapter(arrayList);
            viewPager.setAdapter(adapter);
            ViewGroup.LayoutParams vp_layoutParams = viewPager.getLayoutParams();
            vp_layoutParams.height = dm.widthPixels * 3 / 7;// 设置控件的高强
            viewPager.setLayoutParams(vp_layoutParams); //使设置好的布局参数应用到控件
            viewPager.setCurrentItem(num);
            ses.scheduleWithFixedDelay(mRunnable, 3000, 4000, TimeUnit.MILLISECONDS);

            /*mData = new ArrayList<>();
            gridAdapter = new GridResultAdapter(mData, getActivity());
            gridView.setAdapter(gridAdapter);*/

            tabs.setTabMode(TabLayout.MODE_FIXED);//设置可以滑动
            tabs.setTabGravity(TabLayout.GRAVITY_FILL);
            initDataF(2, "");

            //适配器
            VPAdapter = new
                    VPTabAdapter(getChildFragmentManager(), mDataF, strings);
            vp.setAdapter(VPAdapter);
            //关联tabs 和 ViewPage
            tabs.setupWithViewPager(vp);

            initUI();

            // 设置一个监听器，当ViewPager中的页面改变时调用
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                private int oldPosition = 0;

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    num = position;
                    position = position % arrayList.size();
                    dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
                    dots.get(position).setBackgroundResource(R.drawable.dot_focused);

                    oldPosition = position;

                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

            search.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

            scroll_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(getActivity(),ProductDetailsActivity.class);
                    intent.putExtra("product",mData.get(position));
                    startActivity(intent);
                }
            });

            search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        Intent intent = new Intent(getActivity(), SearchResultActivity.class);
                        intent.putExtra("search_name", search.getText().toString());
                        startActivity(intent);
                        return false;
                    }
                    return false;
                }
            });

            ptr.setMode(PullToRefreshBase.Mode.BOTH);//下拉模式 两种
            ptr.setScrollingWhileRefreshingEnabled(true);//刷新模式仍可以滑动
            ptr.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
                @Override
                public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                    fragment1.loadData("2");
                    fragment2.loadData("3");
                    fragment3.loadData("4");
                    fragment4.loadData("6");
                    loadNetData();
                    ptr.onRefreshComplete();
                }

                @Override
                public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                    fragment1.loadMore("2");
                    fragment2.loadMore("3");
                    fragment3.loadMore("4");
                    fragment4.loadMore("6");
                    ptr.onRefreshComplete();
                }
            });
            initPtrRefresh();

        }

        return v;
    }

    public void initUI() {


        final Product.ListBean pro1 = new  Product.ListBean("水感透白补水套装【洁面+水】",497,"水感透皙亮肤洁面乳125g*1+水感透皙光塑面膜水150ml*1+水感透白净瑕凝乳14g*2（非卖品）+水感透白光塑钻纹弹力面膜一片装*2（非卖品）"
        ,"http://a.vpimg3.com/upload/merchandise/pdc/753/442/4054160438442442753/1/2016031811346-5_235x297_90.jpg",278,
                null,null,13542,"100037");
        final Product.ListBean pro2 = new  Product.ListBean("多效修护粉嫩气色霜50g",130,"多效修护粉嫩气色霜50g ，保养级BB霜，可使肌肤毛孔细纹瞬间隐形，裸妆一步完胜"
                ,"http://a.vpimg3.com/upload/merchandise/pdcvis/2016/09/03/98/758bef63-adde-40a3-b04d-3f40874d8c6a_235x297_90.jpg",109,
                null,null,25424,"100043");
        final Product.ListBean pro3 = new  Product.ListBean("IT°S SKIN伊思晶钻蜗牛套盒清爽型",835,"来自蜗牛体内的粘性蛋白提取物可以提高肌肤弹力，保持肌肤水分。"
                ,"http://a.vpimg2.com/upload/merchandise/pdcvis/2016/09/14/184/c2a6981dd6654cbe8eee98ddbaea0769-5_235x297_90.jpg",479,
                null,null,2546,"100064");
        final Product.ListBean pro4 = new  Product.ListBean("珍珠亮采焕颜青春礼盒",524,"排浊技术，润肤、生肌，从源头净化肤质、祛除黄气，重现青春好气色！"
                ,"http://a.vpimg4.com/upload/merchandise/vis/1423/20011056-549/134/1253234-mz-5_235x297_90.jpg",259,
                null,null,1709,"100058");


            Glide.with(getActivity())
                    .load(pro1.getUrl())
                    .into(aa);
            aa.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ProductDetailsActivity.class);
                    intent.putExtra("product", pro1);
                    startActivity(intent);
                }
            });
            Glide.with(getActivity())
                    .load(pro2.getUrl())
                    .into(imag1);
            imag1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ProductDetailsActivity.class);
                    intent.putExtra("product", pro2);
                    startActivity(intent);
                }
            });
            Glide.with(getActivity())
                    .load(pro3.getUrl())
                    .into(imag2);
            imag2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ProductDetailsActivity.class);
                    intent.putExtra("product",pro3);
                    startActivity(intent);
                }
            });
            Glide.with(getActivity())
                    .load(pro4.getUrl())
                    .into(imag3);
            imag3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ProductDetailsActivity.class);
                    intent.putExtra("product", pro4);
                    startActivity(intent);
                }
            });


    }

    /**
     * 下拉刷新 提示文字
     */
    public void initPtrRefresh() {
        ILoadingLayout startLabels = ptr.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新");
        startLabels.setRefreshingLabel("正在载入...");
        startLabels.setReleaseLabel("放开刷新");
        ILoadingLayout endLabels = ptr.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉刷新");
        endLabels.setRefreshingLabel("正在载入...");
        endLabels.setReleaseLabel("放开刷新...");
    }


    private Runnable mRunnable = new Runnable() {
        public void run() {
            num++;//num 增加
            Message message = viewHandler.obtainMessage(1);
            message.arg1 = num;
            viewHandler.sendMessage(message);
        }

    };

    private final Handler viewHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                viewPager.setCurrentItem(msg.arg1);//ViewPager换到下一页。
            }
            super.handleMessage(msg);
        }

    };


    public void initData() {
        arrayList = new ArrayList<>();
        for (int i = 0; i < imageResId.length; i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setImageResource(imageResId[i]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            arrayList.add(imageView);
        }
        dots = new ArrayList<>();
        // 初始化点图
        dots.add(v.findViewById(R.id.v_dot0));
        dots.add(v.findViewById(R.id.v_dot1));
        dots.add(v.findViewById(R.id.v_dot2));
        dots.add(v.findViewById(R.id.v_dot3));
        dots.add(v.findViewById(R.id.v_dot4));

    }


    private void initDataF(int productType, String search_name) {
        mDataF = new ArrayList<>();
        strings = new ArrayList<>();
        strings.add("人气");
        strings.add("销量");
        strings.add("最新");
        strings.add("价格");

        // 通过序列化传递数据
        // bundle.putSerializable("newsType", types.get(i));
        //  通过Parcelable传递数据
        // bundle.putParcelable("newsType_parcelable",types.get(i));
        fragment1 = new HomeShowFragment();
        Bundle bundle1 = new Bundle();//通过Bundle 携带数据 给 碎片onCreateView()方法使用
        bundle1.putInt("productType", 2);
        bundle1.putString("search_name", search_name);
        bundle1.putInt("id",1);
        fragment1.setArguments(bundle1);
        mDataF.add(fragment1);

        fragment2 = new HomeShowFragment();
        Bundle bundle2 = new Bundle();//通过Bundle 携带数据 给 碎片onCreateView()方法使用
        bundle2.putInt("productType", 3);
        bundle2.putString("search_name", search_name);
        bundle2.putInt("id",2);
        fragment2.setArguments(bundle2);
        mDataF.add(fragment2);

        fragment3 = new HomeShowFragment();
        Bundle bundle3 = new Bundle();//通过Bundle 携带数据 给 碎片onCreateView()方法使用
        bundle3.putInt("productType", 4);
        bundle3.putString("search_name", search_name);
        bundle3.putInt("id",3);
        fragment3.setArguments(bundle3);
        mDataF.add(fragment3);

        fragment4 = new HomeShowFragment();
        Bundle bundle4 = new Bundle();//通过Bundle 携带数据 给 碎片onCreateView()方法使用
        bundle4.putInt("productType", 6);
        bundle4.putString("search_name", search_name);
        bundle4.putInt("id",4);
        fragment4.setArguments(bundle4);
        mDataF.add(fragment4);

    }

    int sec = 59;
    int mins = 19;

    private Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {

                if (mins == 0) {
                    min.setText("00");
                    second.setText("00");
                    return;
                }

                sec = sec -1;
                if (sec == 0) {
                    sec = 59;
                    mins = mins -1;
                    min.setText(mins + "");
                }


                second.setText(sec+"");
            }
        }
    };

    private void loadNetData() {
        circle();;
        OkHttpUtils
                .post()
                .url(Constants.C_URL)
                .addParams("id", "8")
                .addParams("page","1")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyApplication.toast.toastShow("网络异常,请检查网络.");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        img_ads.setVisibility(View.GONE);
                        scroll_lv.setVisibility(View.VISIBLE);
                        Gson gson = new Gson();
                        Product musicWebAlbum = gson.fromJson(response, Product.class);
                        List<Product.ListBean> items = musicWebAlbum.getList();
                        if (mData != null) {
                            mData.clear();
                            mData.addAll(items);
                            hoAdapter.notifyDataSetChanged();
                        }
                        myDialog.dismiss();
                    }
                });

    }


    /**
     * 圆形进度条测试..
     */
    public void circle() {
        myDialog = new CustomProgressDialog(getActivity(),R.style.dialog);
        Window wd= myDialog.getWindow();
        WindowManager.LayoutParams lp = wd.getAttributes();
        lp.alpha = 0.9f;
        wd.setAttributes(lp);
        myDialog.show(); // 显示进度条
    }

}
